﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using Newtonsoft.Json;

using tcm.entity;
using tcm.entity.Device;
using tcm.Filters;
using tcm.request.Device;
using tcm.response;
using tcm.utils;

namespace tcm.Controller.DeviceManage
{
    [ApiController]
    [Route("tcm/command")]
    public class CommandController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public CommandController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }

        #region 远程控制
        /// <summary>
        /// 远程控制站点列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlist")]
        [TCMAuth(permission: "equipment:command:list")]
        public DataResponse<List<ControlDeviceSelect>> GetList()
        {
            var deviceIds = _context.GetAllUserID();
            var tcmList = new List<TCMDeviceRequest>();
            var controlList = new List<ControlDeviceSelect>();
            foreach (var id in deviceIds)
            {
               var info= _context.TryGet<TCMDeviceRequest>(id.ToString()).Result;
                if (info!=null)
                    tcmList.Add(info);
            }

            var list=GCCEntrance.DBManager.GlobalDB.Select<Site>()
                .Where(s =>  s.status==1)
                .OrderByDescending(s => s.create_date)
                .ToList();

            foreach (var item in list)
            {   
                ControlDeviceSelect control = new ControlDeviceSelect();
                var tcmDevice = tcmList.Where(t => t.site_id==item.id).FirstOrDefault();
                if (tcmDevice!=null)
                {
                    control = BeanUtils.copy<ControlDeviceSelect, TCMDeviceRequest>(tcmDevice);
                    control.is_connect=true;
                }else
                    control.is_connect=false;
                 
                control.site_id = item.id;
                control.site_name = item.site_name;
                   
                controlList.Add(control);
            }

            return HandleData(controlList);
        }


        /// <summary>
        /// 发送命令
        /// </summary>
        /// <returns></returns>
        [HttpPost("sendCommand")]
        [TCMAuth(permission: "equipment:command:send")]
        public DataResponse<bool> SendCommand([FromBody] CommandRequest request)
        {
            var saveRes = false;
            if (request.site_id<=0||request.command_type<=0)
                return SystemError<bool>("请求错误");
            try
            {
                var site=GCCEntrance.DBManager.GlobalDB.Select<Site>()
                .Where(d => d.id==request.site_id)
                .First();
                if (site==null)
                    throw new Exception("站点不存在");

                var result = new CommandResult()
                {
                    command_type=request.command_type,
                    site_id=site.id,
                    mac=site.mac
                };

                _context.SendTextMessageToUser(site.id, JsonConvert.SerializeObject(result));
                saveRes=true;
                Logger.Information(String.Format("站点{0}已向远程设备发送命令。", site.site_name), _context.EventID);

            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }

            return HandleData(saveRes);
        }

        #endregion
    }
}
